package com.zjh.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjh.usercenter.model.domain.User;
import com.zjh.usercenter.service.UserService;
import com.zjh.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.zjh.usercenter.controller.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author 27489
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2023-04-15 22:56:06
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;


    private static final String SALT = "hq";



    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1.校验
        //StringUtils.isAnyBlank()判断多个字符串是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return -1;
        }

        if (userAccount.length() < 4) {
            return -1;
        }

        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            return -1;
        }

        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userAccount", userAccount);
        long count = this.count(wrapper);
        if (count > 0) {
            return -1;
        }

        //2.加密
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());


        //3.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(newPassword);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }


        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }

        if (userAccount.length() < 4) {
            return null;
        }

        if (userPassword.length() < 8) {
            return null;
        }

        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }

        //2.加密
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userAccount", userAccount);
        wrapper.eq("userPassword", newPassword);
//        User user = userMapper.selectOne(wrapper);
        User user = this.getOne(wrapper);


        if (user == null) {
            log.info("user login failed");
            return null;
        }

        User safeUser = getsafetyUser(user);

        request.getSession().setAttribute(USER_LOGIN_STATE,safeUser);


        return safeUser;
    }

    @Override
    public User getsafetyUser(User orginUser) {

        User safeUser = new User();
        safeUser.setId(orginUser.getId());
        safeUser.setUsername(orginUser.getUsername());
        safeUser.setUserAccount(orginUser.getUserAccount());
        safeUser.setAvatarUrl(orginUser.getUserPassword());
        safeUser.setGender(orginUser.getGender());
        safeUser.setUserRole(orginUser.getUserRole());
        safeUser.setPhone(orginUser.getPhone());
        safeUser.setEmail(orginUser.getEmail());
        safeUser.setUserStatus(orginUser.getUserStatus());
        safeUser.setCreateTime(orginUser.getCreateTime());

        return safeUser;
    }


}




